﻿using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MyFloridaHouse.libSvOpenDistricts.SummaryDataGrid
{
    // extension class for summaryDataGridManager
    public static class SummaryDataGridIOCSV
    {
        public static MemoryStream DataGridToCSV(this SummaryDataGridManager summaryDataGrid, string fileName)
        {
            MemoryStream CSVmemoryStream = new MemoryStream();
            StreamWriter CSVstreamWriter = new StreamWriter(CSVmemoryStream);

            var columnDescriptionHeadings = from descr in summaryDataGrid.summaryDataGridColumnDescriptionList
                                            select descr.header;
            //write the column headings
            List<string> columnHeaderNames = new List<string>();
            columnHeaderNames.AddRange(columnDescriptionHeadings);
            CSVstreamWriter.WriteLine(string.Join(",", columnHeaderNames));

            // write the data
            foreach (var dataGridRow in summaryDataGrid.dataGridList)
            {
                List<string> newLineValueList = new List<string>();
                int colIndex = 0;
                foreach (var col in summaryDataGrid.summaryDataGridColumnDescriptionList)
                {
                    if (DataGridColumnDescriptionValueType.floatDataType == col.valueType)
                    {
                        newLineValueList.Add(dataGridRow.valuesList[colIndex++].floatValue.ToString());
                    }
                    else if (DataGridColumnDescriptionValueType.intDataType == col.valueType)
                    {
                        newLineValueList.Add(dataGridRow.valuesList[colIndex++].intValue.ToString());
                    }
                    else 
                    {
                        newLineValueList.Add("Error");
                    }
                }
                string newLine = string.Join(",", newLineValueList);
                CSVstreamWriter.WriteLine(newLine);
            }
            CSVstreamWriter.Flush();
            return  CSVmemoryStream;
        }
    }
}
